package com.szgr.baoyin.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.activity.StoreActivity;
import com.szgr.baoyin.activity.StoreDeatilActivity;
import com.szgr.baoyin.adapter.PersonalSaveListAdapter;
import com.szgr.baoyin.model.FavoriteGoods;
import com.szgr.baoyin.myview.NoScrollListView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class PersonalSaveFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {
    private List<FavoriteGoods> data;
    private PersonalSaveListAdapter listAdapter;
    private PersonalInterface pi;
    private View tipView;

    public PersonalSaveFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_personal_save, container, false);
        initView(ret);
        return ret;
    }

    private void initView(View ret) {
        data = new ArrayList<>();
        NoScrollListView saveListView = (NoScrollListView) ret.findViewById(R.id.personal_save_list_view);
        listAdapter = new PersonalSaveListAdapter(getActivity(), data);
        saveListView.setAdapter(listAdapter);
        saveListView.setOnItemClickListener(this);
        tipView = ret.findViewById(R.id.personal_save_tip);
        ret.findViewById(R.id.personal_save_go_store).setOnClickListener(this);

        if(MyApplication.getmInstance().isLogin()) {
            getGoodsList();
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 99:
                    tipView.setVisibility(View.VISIBLE);
                    break;
                case 100:
                    tipView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    /**
     * 收藏商品的列表
     */
    private void getGoodsList() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FAVORITE_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONArray favorites_list = datas.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                data = gson.fromJson(favorites_list.toString(), new TypeToken<List<FavoriteGoods>>() {
                                }.getType());
                                listAdapter.setData(data);
                                if(data.size() > 0){
                                    mHandler.sendEmptyMessage(100);
                                    pi.back(data.size());
                                }else if(data.size() == 0){
                                    mHandler.sendEmptyMessage(99);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("获取收藏列表失败");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("page", "1");
                map.put("pagesize", "100");
                map.put("imgsize", "240");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    public void setListener(PersonalFragment pf) {
        pi = pf;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FavoriteGoods favoriteGoods = data.get(position);
        Intent intent = new Intent(getActivity(), StoreDeatilActivity.class);
        intent.putExtra("goods_id",favoriteGoods.getGoods_id());
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.personal_save_go_store:
                startActivity(new Intent(getActivity(), StoreActivity.class));
                break;
        }
    }

    public interface PersonalInterface{
        void back(int num);
    }
}
